package login;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import news.NewsActivity;
import noten.NotenActivity;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import stundenplan.StundenplanActivity;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import de.app.badresden.R;

public class LoginActivity extends Activity implements OnClickListener {

	private EditText matrikelnummerEditText;
	private EditText passwortEditText;
	private LinearLayout loginContent;

	private Context ctx;
	private String loginreason;
	private SharedPreferences preferences;
	private ProgressDialog progressdialog;
	private String cookievalue;
	private String matrikelnummer;
	private String passwort;
	private int sichtbar = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);
		loginContent = (LinearLayout) findViewById(R.id.login_logincontent);

		matrikelnummerEditText = (EditText) findViewById(R.id.login_matrikelnummer);
		passwortEditText = (EditText) findViewById(R.id.login_passwort);

		ctx = getApplicationContext();
		loginreason = getIntent().getExtras().getString("loginreason");

		preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
		matrikelnummer = preferences.getString("matrikelnummer", "");
		passwort = preferences.getString("passwort", "");

		matrikelnummerEditText.setText(matrikelnummer);

		((Button) findViewById(R.id.login_loginBtn)).setOnClickListener(this);

		if (matrikelnummer.length() != 0 && passwort.length() != 0) {
			login(matrikelnummer, passwort);
		}
		else
			loginContent.setVisibility(sichtbar);
	}

	@Override
	public void onClick(View v) {

		matrikelnummer = matrikelnummerEditText.getText().toString();
		passwort = passwortEditText.getText().toString();

		if (matrikelnummer.length() == 0) {
			showErrorDialog(R.string.error_matrikelnummer_missing_titel,
					R.string.error_matrikelnummer_missing_text);
			return;
		}

		if (passwort.length() == 0) {
			showErrorDialog(R.string.error_passwort_missing_titel,
					R.string.error_passwort_missing_text);
			return;
		}

		CheckBox saveLoginCheckbox = (CheckBox) findViewById(R.id.login_checkboxpasswortsave);

		if (saveLoginCheckbox.isChecked()) {
			Editor edit = preferences.edit();
			edit.putString("matrikelnummer", matrikelnummer);
			edit.putString("passwort", passwort);
			edit.commit();
		}

		login(matrikelnummer, passwort);
	}

	public void login(final String matrikelnummer, final String passwort) {

		progressdialog = ProgressDialog.show(LoginActivity.this,
				getString(R.string.progressdialog_title),
				getString(R.string.progressdialog_login), true);

		Thread loginThread = new Thread() {

			public void run() {

				try {
					synchronized (this) {

						HttpClient httpclient = new DefaultHttpClient();

						HttpPost httppost = new HttpPost(getString(R.string.url_login));
						BufferedReader in = null;

						try {
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
									3);
							nameValuePairs.add(new BasicNameValuePair("matrikelnr",
									matrikelnummer));
							nameValuePairs.add(new BasicNameValuePair("passwort", passwort));
							nameValuePairs.add(new BasicNameValuePair("submit", "LOGIN"));
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

							HttpResponse response = httpclient.execute(httppost);
							Header[] cookieHeaders = response.getHeaders("Set-Cookie");
							cookievalue = cookieHeaders[0].getValue();

							in = new BufferedReader(new InputStreamReader(response.getEntity()
									.getContent()));

							Bundle bundle = new Bundle();
							bundle.putBoolean("login", loginErfolgreich(in));
							Message msg = new Message();
							msg.setData(bundle);
							updateHandler.sendMessage(msg);
						}
						catch (ClientProtocolException e) {
							Log.d("MyApp", e.toString());
						}
						catch (IOException e) {
							Log.d("MyApp", e.toString());
						}
					}
				}
				catch (Exception e) {
					Log.d("MyApp", e.toString());
				}
			}
		};
		loginThread.start();
	}

	private Handler updateHandler = new Handler() {

		public void handleMessage(Message msg) {

			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			boolean loginErfolgreich = bundle.getBoolean("login");

			progressdialog.dismiss();

			if (loginErfolgreich) {
				Bundle extras = new Bundle();
				extras.putString("cookievalue", cookievalue);
				extras.putBoolean("HasInternet",
						getIntent().getExtras().getBoolean("HasInternet"));
				Editor edit = preferences.edit();
				edit.putString("cookie", cookievalue);
				edit.commit();
				loginAbschliessen(extras);
			}
			else {
				showErrorDialog(R.string.error_login_missing_titel,
						R.string.error_login_wronglogin_text);
			}
		}
	};

	private void loginAbschliessen(Bundle bundle) {

		Intent intent = new Intent();
		intent.putExtras(bundle);

		if (loginreason.equals("noten")) {
			intent.setClass(ctx, NotenActivity.class);
			finish();
			startActivity(intent);
		}

		if (loginreason.equals("stundenplan")) {
			intent.setClass(ctx, StundenplanActivity.class);
			finish();
			startActivity(intent);
		}

		if (loginreason.equals("news")) {
			intent.setClass(ctx, NewsActivity.class);
			finish();
			startActivity(intent);
		}
	}

	private boolean loginErfolgreich(BufferedReader in) throws IOException {

		String tmp;
		while (((tmp = in.readLine())) != null) {
			if (tmp.contains("Nachrichten")) {
				return true;
			}
		}
		return false;
	}

	private void showErrorDialog(int titel, int hinweistext) {

		loginContent.setVisibility(sichtbar);

		final Dialog dialog = new Dialog(LoginActivity.this);
		dialog.setCancelable(false);
		dialog.setContentView(R.layout.login_dialoglayout);
		dialog.setTitle(titel);

		TextView text = (TextView) dialog.findViewById(R.id.hinweisdialog_text);
		text.setText(hinweistext);

		Button m = (Button) dialog.findViewById(R.id.hinweisdialog_button);
		m.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				passwortEditText.setText("");
				dialog.cancel();
			}
		});
		dialog.show();
	}
}